import json
import pymysql
import os
from datetime import datetime

def safe_int(value, default=0):
    """安全转换为整数，处理空值、字符串逗号和异常"""
    try:
        return int(str(value).replace(',', '').strip())
    except:
        return default

# 数据库配置
config = {
    'host': 'localhost',
    'user': 'root',
    'password': '', #密码
    'database': 'compareprice',
    'charset': 'utf8mb4'
}

# 读取JSON文件
json_path = r""#路径

if not os.path.exists(json_path):
    print(f"错误：文件不存在！请检查路径:\n{json_path}")
else:
    print("文件路径验证通过！")
    with open(json_path, 'r', encoding='utf-8') as f:
        data = json.load(f)

# 连接数据库
conn = pymysql.connect(**config)
cursor = conn.cursor()

for item in data:
    # 只是示例，记得根据自己建的表来改
    cursor.execute("""
        INSERT INTO products (
            title, current_price, deal_num, comment_num, 
            shop, title_url, shop_url, image_url, created_at
        ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
    """, (
        item.get('title', '').replace('\n', ' ').strip(),
        float(item.get('Price', 0)),
        safe_int(item.get('Deal')),
        safe_int(item.get('Review')),
        item.get('Shop', ''),
        f"https:{item.get('Title_URL', '')}" if item.get('Title_URL') else None,
        f"https:{item.get('Shop_URL', '')}" if item.get('Shop_URL') else None,
        item.get('Img_URL'),
        datetime.now()
    ))

conn.commit()
conn.close()
print(f"成功导入 {len(data)} 条数据！")